Param(
    [string]$BaseUrl = "http://localhost:8080"
)

Write-Host "[Smoke] Starting API smoke tests against $BaseUrl"

function Invoke-JsonPost($url, $body) {
    return Invoke-RestMethod -Method Post -Uri $url -ContentType 'application/json' -Body ($body | ConvertTo-Json -Depth 5)
}

function Assert($cond, $msg) {
    if (-not $cond) { throw "ASSERT FAILED: $msg" }
}

# 1) Auth login success
$resp = Invoke-JsonPost "$BaseUrl/api/auth/login" @{ username = 'merchant1'; password = '1234'; userType = 'merchant' }
Assert ($resp.username -eq 'merchant1') 'login username should be merchant1'

# 2) List merchants
$merchants = Invoke-RestMethod "$BaseUrl/api/merchants"
Assert ($merchants.Length -ge 1) 'merchants should not be empty'

# 3) Create dish -> update -> delete
$dish = Invoke-JsonPost "$BaseUrl/api/dishes" @{ merchantId = 2; name = 'PS测试菜品'; price = 9.9; category = '测试' }
Assert ($dish.id -gt 0) 'created dish id should be > 0'
$updated = Invoke-RestMethod -Method Put -Uri "$BaseUrl/api/dishes/$($dish.id)" -ContentType 'application/json' -Body (@{ price = 19.9 } | ConvertTo-Json)
Assert ($updated.price -eq 19.9) 'updated dish price should be 19.9'
Invoke-RestMethod -Method Delete -Uri "$BaseUrl/api/dishes/$($dish.id)"

# 4) Create order -> patch status
$order = Invoke-JsonPost "$BaseUrl/api/orders" @{ userId=1; merchantId=2; dishes=@(@{ id=1; name='宫保鸡丁'; price=28.0; quantity=1 }); totalPrice=28.0; deliveryFee=5.0; finalPrice=33.0; deliveryAddress='地址'; customerPhone='13800138000'; customerName='PS' }
Assert ($order.id -gt 0) 'order id should be > 0'
$order2 = Invoke-RestMethod -Method Patch -Uri "$BaseUrl/api/orders/$($order.id)" -ContentType 'application/json' -Body (@{ status = 'preparing' } | ConvertTo-Json)
Assert ($order2.status -eq 'preparing') 'order status should be preparing'

# 5) Rider location add
$loc = Invoke-JsonPost "$BaseUrl/api/rider-locations" @{ riderId=3; latitude=39.9; longitude=116.4 }
Assert ($loc.id -gt 0) 'rider location id should be > 0'

Write-Host "[Smoke] All checks passed."


